package com.ruoyi.project.erp.sos.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.project.erp.Item.domain.TItem;
import com.ruoyi.project.erp.Item.service.ITItemService;
import com.ruoyi.project.erp.setupbill.service.ISetupbillService;
import com.ruoyi.project.erp.so.domain.So;
import com.ruoyi.project.erp.so.service.ISoService;
import com.ruoyi.project.erp.sossend.domain.Sossend;
import com.ruoyi.project.erp.sossend.service.ISossendService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.erp.sos.domain.Sos;
import com.ruoyi.project.erp.sos.service.ISosService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2020-08-25
 */
@Controller
@RequestMapping("/erp/sos")
public class SosController extends BaseController
{
    private String prefix = "erp/sos";

    @Autowired
    private ISosService sosService;
    @Autowired
    private ISossendService sossendService;
    @Resource
    private ISoService soService;
    @Autowired
    private ITItemService tItemService;
    @Autowired
    private ISetupbillService setupbillService;
    @RequiresPermissions("erp:sos:view")
    @GetMapping()
    public String sos()
    {
        return prefix + "/sos";
    }


 /*   *//**
     * 批量更新
     *//*
    @PostMapping(value = "/batckUpdate",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public AjaxResult batckUpdate(@RequestBody List<Map> list)
    {
        int num = 0;
        for(int i=0;i<list.size();i++){
            Map<Object,Object> temp = list.get(i);
            Sos sos = new Sos();
            for (Map.Entry<Object,Object> entry : temp.entrySet()) {
                if("id".equals(entry.getKey())){
                    sos.setId(Long.parseLong(entry.getValue().toString()));
                }
                if("sendqty".equals(entry.getKey())){
                    sos.setSendqty(Integer.parseInt(entry.getValue().toString()));
                }
            }
            if(EmptyUtils.isNotEmpty(sos.getId()) && sos.getSendqty() >0){
                num +=sosService.updateSos(sos);
            }
        }
        return toAjax(num);
    } */

    /**
     * 批量更新
     */
    @RepeatSubmit
    @PostMapping(value = "/batckUpdate",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public AjaxResult batckUpdate(@RequestBody List<Map> list,String sendcode,String smemo,String logcode,String mid,String isreplace,String fromwh,String fromwhname)
    {
        int num = 0;
        Date senddt = new Date();
        for(int i=0;i<list.size();i++){
            Map<Object,Object> temp = list.get(i);
            String sosId="";
            String sosSt="发货中";
            Sossend sossend = new Sossend();
            sossend.setIds(Long.parseLong(mid));
            sossend.setLogcode(logcode);
            sossend.setSendcode(sendcode);
            sossend.setSmemo(smemo);
            sossend.setSenddt(senddt);
            sossend.setFromwh(fromwh);
            sossend.setFromwhname(fromwhname);
            sossend.setSt("发货");
            sossend.setIsreplace(isreplace);
            for (Map.Entry<Object,Object> entry : temp.entrySet()) {
                if("currentSendqty".equals(entry.getKey())){
                    sossend.setSendqty(Integer.parseInt(entry.getValue().toString()));
                }
                if("id".equals(entry.getKey())){
                    sosId=entry.getValue().toString();
                    sossend.setIdsos(Long.parseLong(sosId));
                }
                if("pcode".equals(entry.getKey())){
                    sossend.setPcode(entry.getValue().toString());
                }
                if("pname".equals(entry.getKey())){
                    sossend.setPname(entry.getValue().toString());
                }
                if("itemcode".equals(entry.getKey())){
                    sossend.setItemcode(entry.getValue().toString());
                }
                if("pstd".equals(entry.getKey())){
                    if(entry.getValue() != null) {
                        sossend.setPstd(entry.getValue().toString());
                    }
                }
                if("sts".equals(entry.getKey())){
                    sosSt = entry.getValue().toString();
                }
            }
            if(sossend.getSendqty()>0 && !"发货完成".equals(sosSt)){
                int currNum = sossendService.insertSossend(sossend);
                num += currNum;
                if(currNum>0){
                    //判断是否发货完毕,修改发货数量
                    Sos sos = sosService.selectSosById(Long.parseLong(sosId));
                    Sos sos1 = new Sos();
                    sos1.setId(Long.parseLong(sosId));
                    if(sos.getQty() == (sos.getSendqty()+sossend.getSendqty())){
                        sos1.setSts("发货完成");
                        sos1.setSendqty(sos.getSendqty()+sossend.getSendqty());
                    }else{
                        sos1.setSts("发货中");
                        sos1.setSendqty(sos.getSendqty()+sossend.getSendqty());
                    }
                    sosService.updateSos(sos1);
                    //判断主表是否发货完毕
                    So so = soService.selectSoById(mid);
                    //查询所有子表是否发货完毕
                    Sos sos2 =new Sos();
                    sos2.setMid(Long.parseLong(mid));
                    List<Sos> sosList = sosService.selectSosList(sos2);
                    int m=0;
                    So so1 = new So();
                    so1.setId(so.getId());
                    for(Sos tempSos :sosList){
                        if(!"发货完成".equals(tempSos.getSts())){
                            so1.setSt("发货中");
                            break;
                        }
                        m++;
                    }
                    if(m>=sosList.size()){
                        so1.setSt("发货完成");
                    }
                    soService.updateSo(so1);
                }
            }
        }

        //如果厂家代发，自动生成调拨单，不显示生单按钮
        if("否".equals(isreplace)){
            soService.updateJDinfo(1,sendcode);
            Sossend sossend1 = new Sossend();
            //修改生单状态
            sossend1.setSendcode(sendcode);
            sossend1.setKingst("1");
            sossend1.setIds(Long.parseLong(mid));
            sossendService.updateSossendBatch(sossend1);
        }
        return toAjax(num);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("erp:sos:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(long mid)
    {
        //startPage();
        Integer pageNum = ServletUtils.getParameterToInt(Constants.PAGE_NUM);
        Integer pageSize =ServletUtils.getParameterToInt(Constants.PAGE_SIZE);
        Sos sos =new Sos();
        sos.setMid(mid);
        List<Sos> list = sosService.selectSosList(sos);
        List<Sos> resultList = new ArrayList<>();
        int totalPage = list.size()/pageSize+1;
        int count = pageNum*pageSize;
        if (pageNum == totalPage){
            count = list.size();
        }
        for(int start = (pageNum-1)*pageSize;start<count;start++){
            resultList.add(list.get(start));
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(resultList);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("erp:sos:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Sos sos)
    {
        List<Sos> list = sosService.selectSosList(sos);
        ExcelUtil<Sos> util = new ExcelUtil<Sos>(Sos.class);
        return util.exportExcel(list, "sos");
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    //@RequiresPermissions("erp:sos:add")
    //@Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody Sos sos)
    {
        return toAjax(sosService.insertSos(sos));
    }

    /**
     * 修改【请填写功能名称】
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Sos sos = sosService.selectSosById(id);
        mmap.put("sos", sos);
        return prefix + "/edit";
    }

    /**
     * 修改【请填写功能名称】
     */
    @GetMapping("/view/{mid}")
    public String view(@PathVariable("mid") Long mid, ModelMap mmap)
    {
        mmap.put("mid", mid);
        //返回发货单
        So so = soService.selectSoById(mid.toString());
        StringBuffer sb = new StringBuffer();
        sb.append(so.getCode());
        //判断是否有发货记录
        Sossend sossend = new Sossend();
        sossend.setIds(mid);
        List<Sossend> sossendList = sossendService.selectSossendList(sossend);
        if(sossendList.size()>0){
            String maxCode=sossendList.get(0).getSendcode();
            for(int i=1;i<sossendList.size();i++){
                   if(maxCode.compareTo(sossendList.get(i).getSendcode())<0){
                        maxCode = sossendList.get(i).getSendcode();
                   }
            }
            int suffix = Integer.parseInt(maxCode.substring(12))+1;
            sb.append(suffix);
        }else{
            sb.append("1");
        }
        mmap.put("sendcode", sb.toString());
        mmap.put("items",tItemService.listToName());
        return prefix + "/sos";
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @RequiresPermissions("erp:sos:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Sos sos)
    {
        return toAjax(sosService.updateSos(sos));
    }

    /**
     * 删除【请填写功能名称】
     */
    //@RequiresPermissions("erp:sos:remove")
    //@Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sosService.deleteSosByIds(ids));
    }

    /**
     * 查询发货详情
     */
    @PostMapping("/listSosSend")
    @ResponseBody
    public AjaxResult listSosSend(long id)
    {
        Sossend sossend = new Sossend();
        sossend.setIds(id);
        return new AjaxResult(AjaxResult.Type.SUCCESS,"200",sossendService.selectSossendList(sossend));
    }
}
